<!-- 文本输入框 -->
<template>
<div class="text" id="text">
    <div class="emoji">
          <i class="icon iconfont icon-look" @click="showEmoji=!showEmoji"></i>
          <transition name="showbox">
             <div class="emojiBox" v-show="showEmoji">
                 <li v-for="(item, index) in emoji" :key="index" @click="emojiIcon(item)">{{item}}</li>
             </div>
          </transition>
    </div>
    <el-upload
        class="avatar-uploader"
        :action="server"
        :show-file-list="false"
        :data="fromData"
        :before-upload="beforeAvatarUpload"
        :on-success="handleAvatarSuccess"
        >
        <div class="picture-file"></div>
    </el-upload>
    <textarea ref="text" v-model="content" @keyup="onKeyup" @click="showEmoji=false"></textarea>
    <div class="send" @click="send">
    	<span>发送(ent)</span>
    </div>
    <transition name="appear">
	    <div class="warn" v-show="warn">
	    	<div class="description">不能发送空白信息</div>
	    </div>
	</transition>
</div>
</template>

<script>
import { mapGetters, mapState, mapActions } from 'vuex'
import mqtt from '../../libs/mqtt'
import { _getUploadTokenResult } from '../../pbApi/pb_WFCMessage'
import { resizeImage, base64ToArrayBuffer } from '../../libs/util'
import emoji from 'emoji'

export default {
    components:{
       
    },
    data () {
        return {
            emoji:[],
            content: '',
            reply: '未找到',
            frequency: 0,
            warn: false,
            showEmoji: false,
            // 图片上传
            domain:'',
            port:'',
            server:'',
            fromData:{
                token:""
            },
        }
    },
    created(){
        for(let v in emoji.EMOJI_MAP) {
            this.emoji.push(v)
        }
    },
    computed: {
        ...mapState({
            selectId: state => state.chat.selectId,
            chatlist: state => state.chat.chatlist
        }),
        ...mapGetters([
            'selectedChat',
        ])
    },
    methods: {
        //  上传
        ...mapActions(["UPLOAD"]),
        // 按回车发送信息
        onKeyup (e) {
            if ( e.keyCode === 13 ) {
               this.send()
            }
        },
        // 点击发送按钮发送信息
        send () {
            let _this = this
            if(!this.content.trim() || this.content.length < 0){
                this.warn = true
                this.content = ''
                setTimeout(() => {
                    this.warn = false;
                }, 1000)
            }else{
                let obj = _this.chatlist.find(item => _this.selectId == item.uid)
                var msg = {
                    conversationType: obj.type,
                    content: this.content.trim(),
                    type: 1   //文字发送
                }
                this.$store.dispatch('sendMessage', msg)
                this.content = ''
            }
        },
        // 选择表情
        emojiIcon(emo){
            this.content += emo
            this.showEmoji = false
        },
        // 上传文件之前
        beforeAvatarUpload(file){
            var _this = this
            return new Promise((resolve, reject) => {
                var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|'
                var isGS = '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1
                var isLt2M = file.size / 1024 / 1024 < 2;
                if(!isGS){
                    this.$message.error('图片格式只能是 JPG/PNG/JPEG/BMP/GIF 格式!')
                }
                if(!isLt2M){
                    this.$message.error('发送图片大小不能超过 2MB!')
                }
                if(isGS&&isLt2M){
                    var reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = function(){
                        let obj = _this.chatlist.find(item => _this.selectId == item.uid)
                        var msg = {
                            conversationType: obj.type,
                            content: '[图片]',
                            type: 3,   //图片发送this.domain+'/'+res.hash
                            remoteMediaUrl: reader.result,
                            data: ''
                        }
                        resizeImage(reader.result,(data)=>{
                            msg.data = data
                            _this.$store.dispatch('sendPhoto', msg)
                        },120,100)
                        resolve()
                    }
                }
            }).then(() => {
                return new Promise((resolve, reject) => {
                    mqtt.mqttPublish('GQNUT', "1", (res) => {
                        let data = _getUploadTokenResult(res)
                        this.domain = data.domain
                        this.server = 'http://'+data.server
                        this.port = data.port
                        this.fromData.token = data.token
                        resolve()
                    })
                })
            })
        },
        // 上传成功
        handleAvatarSuccess(res, file){
            let _this = this
            let obj = this.chatlist.find(item => this.selectId == item.uid)
            console.log(obj.messages[obj.messages.length - 1])
            var msg = {
                conversationType: obj.type,
                content: obj.messages[obj.messages.length - 1].content,
                type: obj.messages[obj.messages.length - 1].type,   //图片发送this.domain+'/'+res.hash
                mediaType: 1,
                remoteMediaUrl: this.domain+'/'+res.hash,
                data: base64ToArrayBuffer(obj.messages[obj.messages.length - 1].data)
            }
            this.$store.dispatch('handlePhotoRes', msg)
        }
    },
    // 在进入的时候 聚焦输入框
    mounted() {
        this.$refs.text.focus()

      let WH = $(window).height();

      if(WH>860){
        $('.message-wrapper').css({'min-height':'630px','max-height':'630px'});
        $('#text').css('margin-top','150px');
      }else{
        $('.message-wrapper').css({'min-height':'485px','max-height':'485px'});
        $('#text').css('margin-top','0px');
      }
        // console.log(53614356456)
    },
    watch: {
        // 在选择其它对话的时候 聚焦输入框
        selectId() {
          setTimeout(() => {
            this.$refs.text.focus()
          }, 0)
        },
        // 当输入框中的值为空时 弹出提示  并在一秒后消失
        content() {
            if(this.content === ''){
                if( this.frequency === 0){
                  this.warn = true;
                  this.frequency++
                  setTimeout(() => {
                    this.warn = false;
                  }, 1000)
                }
            }
        }
    }
}
</script>

<style lang="stylus" scoped>
.text
    position: relative
    height: 211px
    background: #f2f2f2
    .emoji
        float left
        position: relative
        height: 40px
        line-height: 40px
        font-size: 12px
        padding: 0 30px
        box-sizing: border-box
        color: #7c7c7c
        /*border-top :1px solid #e7e7e7*/
        .icon-look
            cursor: pointer
            &:hover
                color: #1aad19
        .emojiBox
            overflow-y: auto
            position: absolute
            display: flex
            flex-wrap: wrap
            top: -260px
            left: -150px
            width: 450px
            height: 250px
            padding: 5px
            background-color: #fff
            border: 1px solid #d1d1d1
            border-radius: 2px
            box-shadow:0 1px 2px 1px #d1d1d1
            &.showbox-enter-active, &.showbox-leave-active
                transition: all .5s
            &.showbox-enter,&.showbox-leave-active
                opacity: 0
            li {
                cursor pointer
                font-size 14px
                margin 0 2px
            }
    .picture-file {
        margin-top 10px;
        float left;
        width 20px;
        height 20px;
        background url('../../assets/img/icon-wenjian@2x.png') no-repeat;
        background-size cover;
        cursor pointer;
    }
    textarea
        box-sizing: border-box
        padding: 0 30px
        height: 110px
        width: 100%
        border: none
        outline: none
        font-family: "Micrsofot Yahei"
        resize: none
        background :#f2f2f2
    .send
        position: absolute
        cursor pointer
        bottom: 10px
        right: 30px
        width: 75px
        height: 28px
        line-height: 28px
        box-sizing: border-box
        text-align: center
        border: 1px solid #e5e5e5
        border-radius: 3px
        background: #f5f5f5
        font-size: 14px
        color: #7c7c7c
        &:hover
            background: rgb(18,150,17)
            color: #fff
    .warn
         position: absolute
         bottom: 50px
         right: 10px
         width: 110px
         height: 30px
         line-height: 30px
         font-size: 12px
         text-align: center
         border: 1px solid #bdbdbd
         border-radius: 4px
         box-shadow:0 1px 5px 1px #bdbdbd
         &.appear-enter-active, &.appear-leave-active
            transition: all 1s
         &.appear-enter,&.appear-leave-active
            opacity: 0
         &:before
            content: " "
            position: absolute
            top: 100%
            right: 20px
            border: 7px solid transparent
            border-top-color: #fff
            filter:drop-shadow(1px 3px 2px #bdbdbd)
            
</style>
